#!/usr/bin/env python
"""
Acorn-SDR (A Collaboration of Radio Nodes)
(c) Bob Cowdery (G3UKB) 2009

File: dsp_service.py
Date: April 2009

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

The author can be reached by email at

bob@g3ukb.co.uk

================================================================================
Module Description:

The interface service for HPSDR Ozy. This service includes a tightly coupled DSP.

"""

#-------------------------------------------------------------------------------
# System imports
import sys
import os
from types import *
from time import sleep

# These imports are not needed in this module but ...
from scipy.signal.signaltools import resample
from numpy import *
from scipy import signal
# because of a fault in Ice they must be imported first
import Ice, IceStorm

# Application imports
import utils
import dsp
import ozy
import ice_helpers

# Import the Ice interface definitions
import AcornLifeCycle
import AcornRxUpdate
import AcornRxDsp
import AcornIqIn
import AcornRxOut
import AcornRxControl
import AcornPersist

#===============================================================================
# Ice life-cycle events for the Ozy DSP service
class LifeCycleI(AcornLifeCycle.LifeCycle):
    
    #---------------------------------------------------------------------------   
    def __init__(self, service, ozy_impl):
        self.ozy_impl = ozy_impl
        self.service = service
      
    #---------------------------------------------------------------------------
    def start(self, current=None):
        self.ozy_impl.power_on()
     
    #---------------------------------------------------------------------------   
    def stop(self, current=None):
        self.ozy_impl.power_off()
    
    #---------------------------------------------------------------------------    
    def terminate(self, current=None):
        self.service.terminate()
        
#===============================================================================
# Commands for HPSDR
# Ice command events for the Ozy Controller
class RxControlI(AcornRxControl.RxControl):
    
    #---------------------------------------------------------------------------   
    def __init__(self, service, ozy_impl):
      self.ozy_impl = ozy_impl
      self.service = service
        
    #---------------------------------------------------------------------------   
    def freqSet(self, freq, current=None):
        self.ozy_impl.freq_set(freq)
        
    #---------------------------------------------------------------------------   
    def freqInc(self, inc, current=None):
        self.ozy_impl.freq_inc(inc)
    
    #---------------------------------------------------------------------------   
    def mox(self, state, current=None):
        self.ozy_impl.freq_inc(state)

#===============================================================================
# Commands for the DSP
class RxDspI(AcornRxDsp.RxDsp):
    
    #---------------------------------------------------------------------------   
    def __init__(self, service, dsp_impl):
        self.dsp_impl = dsp_impl
        self.service = service
        
    #---------------------------------------------------------------------------
    def setMode(self, mode, current=None):
        self.dsp_impl.set_mode(mode)
    
    #---------------------------------------------------------------------------    
    def setFilter(self, filter, current=None):
        self.dsp_impl.set_filter(filter)
    
    #---------------------------------------------------------------------------    
    def setAgcState(self, state, current=None):
        self.dsp_impl.set_agc_state(state)
    
    #---------------------------------------------------------------------------    
    def setAgcRate(self, rate, current=None):
        self.dsp_impl.set_agc_rate(rate)

#===============================================================================
# Ice config events for OzyDsp
class RxConfigI(AcornRxUpdate.RxConfig):
    
    #---------------------------------------------------------------------------   
    def __init__(self, ozy_impl, dsp_impl, persist, ozy_config_map, dsp_config_map):
        self.ozy_impl = ozy_impl
        self.dsp_impl = dsp_impl
        self.persist = persist
        self.ozy_map = ozy_config_map
        self.dsp_map = dsp_config_map
      
    #---------------------------------------------------------------------------   
    def configUpdate(self, name, current=None):
        # Update the Ozy configuration
        if name in self.ozy_map:
            # Its something we are interested in so go get it
            item = utils.persist_get(self.persist, 'Profile', name)
            # and pass it in
            self.ozy_map[name](item)
        if name in self.dsp_map:
            # Its something we are interested in so go get it
            item = utils.persist_get(self.persist, 'Profile', name)
            # and pass it in
            self.dsp_map[name](item)
            
#===============================================================================
class OzyDspService(Ice.Application):
    
    #---------------------------------------------------------------------------
    def __init__(self):       
        self.close = False
    
    #---------------------------------------------------------------------------
    # Run the app
    def run(self, args):
       
       #-----------------------------------------------------------------------
        # persist interface
        persist = ice_helpers.get_interface('Ozy Service', self.communicator, AcornPersist.PersistPrx, 'Persist.Proxy')
        # Get config
        ramp = utils.persist_get(persist, 'Profile', 'dsp.agcramp')
        gain = utils.persist_get(persist, 'Profile', 'dsp.agcgain')
        roof = utils.persist_get(persist, 'Profile', 'dsp.agcroof')
        frames = utils.persist_get(persist, 'Profile', 'audio.frames')
        rate = utils.persist_get(persist, 'Profile', 'audio.rate')
        rf_gain = utils.persist_get(persist, 'Dynamic', 'gain')
        stream_to = utils.persist_get(persist, 'Profile', 'audio.output')
        ref = utils.persist_get(persist, 'Profile', 'hpsdr.ref')
        src = utils.persist_get(persist, 'Profile', 'hpsdr.src')
        config = utils.persist_get(persist, 'Profile', 'hpsdr.config')
        mic = utils.persist_get(persist, 'Profile', 'hpsdr.mic')
        
        #-----------------------------------------------------------------------
        # Event names used here
        publish_to_rx_updates = 'rx_update_events'
        subscribe_to_rx_config = 'rx_config_events'
        subscribe_to_rx_control = 'rx_control_events'
        subscribe_to_rx_dsp = 'rx_dsp_events'
        subscribe_to_lc = 'life_cycle_events'
  
        #-----------------------------------------------------------------------
        # This is the same for both publishers and subscribers
        # Get the IceStorm topic manager interface
        manager = ice_helpers.get_topic_manager('Ozy DSP Service', self.communicator)
        
        # Retrieve the subscriber topic
        rx_control_topic = ice_helpers.get_topic('Ozy DSP Service', manager, subscribe_to_rx_control)
        rx_dsp_topic = ice_helpers.get_topic('Ozy DSP Service', manager, subscribe_to_rx_dsp)
        life_cycle_topic = ice_helpers.get_topic('Ozy DSP Service', manager, subscribe_to_lc)
        rx_config_topic = ice_helpers.get_topic('Ozy DSP Service', manager, subscribe_to_rx_config)
        
        # Retrieve the publisher topic
        publisher_topic = ice_helpers.get_topic('Ozy DSP Service', manager, publish_to_rx_updates)
  
        #-----------------------------------------------------------------------
        # Publisher side
        # Get the topic's publisher object, and create an update proxy
        publisher = publisher_topic.getPublisher();
        publisher = publisher.ice_oneway();        
        rx_update_publisher = AcornRxUpdate.RxUpdatePrx.uncheckedCast(publisher)
        
        #-----------------------------------------------------------------------
        # Initialise the Ozy as its needed for the adapter and requires the update publisher
        ozy_impl = ozy.Ozy(persist, rx_update_publisher, ref, src, config, mic, frames, rate)
        ozy_config_map = {'audio.frames': ozy_impl.set_audioframes, 'audio.rate': ozy_impl.set_audiorate}
        
        #-----------------------------------------------------------------------
        # Initialise the Dsp as its needed for the adapter and requires the update publisher
        dsp_impl = dsp.Dsp(rx_update_publisher, rf_gain, ramp, gain, roof, frames, rate)
        dsp_config_map = {'dsp.agcramp': dsp_impl.set_agcramp,'dsp.agcgain': dsp_impl.set_agcgain,'dsp.agcroof': dsp_impl.set_agcroof,'audio.frames': dsp_impl.set_audioframes, 'audio.rate': dsp_impl.set_audiorate}
        
        #-----------------------------------------------------------------------
        # Subscriber side
        # Create an adapter for the subscriber dsp interface
        adapter_1 = self.communicator().createObjectAdapter("RxDsp.Subscriber")
        subId_1 = Ice.Identity()
        subId_1.name = Ice.generateUUID()
        # Add the update interface to the adapter
        subscriber_1 = adapter_1.add(RxDspI(self, dsp_impl), subId_1)
        # Subscribe to the topic - set up proxy
        ice_helpers.subscribe('Ozy DSP Service', rx_dsp_topic, subscriber_1, id)
        # Now we can receive callbacks   
        adapter_1.activate()
        
        # Create an adapter for the subscriber command interface
        adapter_2 = self.communicator().createObjectAdapter("RxControl.Subscriber")
        subId_2 = Ice.Identity()
        subId_2.name = Ice.generateUUID()      
        # Add the update interface
        subscriber_2 = adapter_2.add(RxControlI(self, ozy_impl), subId_2)
        # Subscribe to the topic - set up proxy
        ice_helpers.subscribe('Ozy Dsp Service', rx_control_topic, subscriber_2, id)
        # Now we can receive callbacks   
        adapter_2.activate()
        
        adapter_3 = self.communicator().createObjectAdapter("LifeCycle.Subscriber")
        subId_3 = Ice.Identity()
        subId_3.name = Ice.generateUUID()        
        # Add the update interface
        subscriber_3 = adapter_3.add(LifeCycleI(self, ozy_impl), subId_3)
        # Subscribe to the topic - set up proxy
        ice_helpers.subscribe('Ozy Dsp Service', life_cycle_topic, subscriber_3, id)
        # Now we can receive callbacks   
        adapter_3.activate() 
        
        adapter_4 = self.communicator().createObjectAdapter("RxConfig.Subscriber")
        subId_4 = Ice.Identity()
        subId_4.name = Ice.generateUUID()        
        # Add the update interface
        subscriber_4 = adapter_4.add(RxConfigI(ozy_impl, dsp_impl, persist, ozy_config_map, dsp_config_map), subId_4)
        # Subscribe to the topic - set up proxy
        ice_helpers.subscribe('Ozy DSP Service', rx_config_topic, subscriber_4, id)
        # Now we can receive callbacks   
        adapter_4.activate()
        
        #-----------------------------------------------------------------------
        # One way audio channel out
        # Set up the proxy
        # The stream can be split for remote HPSDR or single
        stream_out = None
        if stream_to == 'both':
            stream_out = ice_helpers.get_interface('Ozy DSP Service', self.communicator, AcornRxOut.RxOutPrx, 'RxOut.Proxy')
            streamOneway = AcornRxOut.RxOutPrx.uncheckedCast(stream_out.ice_oneway())
        
        print 'Acorn-SDR (Ozy DSP Service) running..'
        
        #-----------------------------------------------------------------------
        # main loop
        while not self.close:
            # Need a break out of this loop for a close
            try:
                # Get the next audio block and push through the dsp
                samples = ozy_impl.capture()
                # Use for non-threaded
                #if samples:
                # Use for threaded
                if (type(samples) == TupleType):
                    samples_as_double = asarray(samples, 'd')
                    real_out = dsp_impl.do_rx(samples_as_double)
                    real_out_as_float = real_out.astype('f')
                    sleep(0.001)
                    ozy_impl.output(real_out_as_float)
                    if stream_to == 'both':
                        stream_out.data(real_out_as_float.tolist())
                else:
                    sleep(0.001)
                ozy_impl.write()
            except IOError, e:
                # Ignore
                pass
            except Ice.CommunicatorDestroyedException, e:
                # Ignore
                pass

        # Unsubscribe all subscribed objects.
        # Seems to cause issues
        #dsp_topic.unsubscribe(subscriber_1)
        #ozy_topic.unsubscribe(subscriber_2)
        #life_cycle_topic.unsubscribe(subscriber_3)
    
    #---------------------------------------------------------------------------
    # Terminate
    def terminate(self):
        self.close = True
        
#===============================================================================
#===============================================================================
# Start from the command line
if __name__ == "__main__":
   
    app = OzyDspService()
    app.main(sys.argv, sys.argv[1])
  
    # Announce we are going 
    print 'Acorn-SDR  (Ozy DSP Service) closing..'






